package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.edu.nju.ws.sview.LogManagement;
import cn.edu.nju.ws.sview.views.User;

/**
 * Servlet implementation class Logout
 */
@WebServlet("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
//	private Logger logger = Logger.getLogger(Logout.class.getName()) ;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		String displayLang = (String) request.getParameter("lang");
		String user = (String)request.getSession().getAttribute("user") ;
		int userId = User.getUserIdByName(user);

		LogManagement.storeLogInOut(userId, LogManagement.EVENT_LOGOUT, displayLang);
		String from = (String) request.getParameter("from");
		request.getSession().removeAttribute("user") ;
		request.getSession().invalidate();
		if(from!=null){
			from = URLDecoder.decode(from, "UTF-8");
			response.sendRedirect(from) ;
		}else{
			response.sendRedirect("/sview/login.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
